package com.keyou.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.keyou.reggie.common.ResultInfo;
import com.keyou.reggie.dto.DishDTO;
import com.keyou.reggie.dto.SetmealDTO;
import com.keyou.reggie.entity.Category;
import com.keyou.reggie.entity.Dish;
import com.keyou.reggie.entity.SetMeal;
import com.keyou.reggie.entity.SetmealDish;
import com.keyou.reggie.service.CategoryService;
import com.keyou.reggie.service.DishService;
import com.keyou.reggie.service.SetMealService;
import com.keyou.reggie.service.SetmealDishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author: klq
 * @Date: 2023/1/10 16:49
 * @Description:
 */
@Slf4j
@RestController
@RequestMapping(value = "/setmeal")
public class SetMealController {

    @Autowired
    private SetMealService setMealService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private DishService dishService;


    /**
     * 新增套餐
     *
     * @param setmealDTO
     * @return
     */
    //设置allEntries为true，清空缓存名称为setmealCache的所有缓存
    @CacheEvict(value = "setmealCache", allEntries = true)
    @PostMapping
    public ResultInfo<String> save(@RequestBody SetmealDTO setmealDTO) {
        log.info("套餐信息：{}", setmealDTO);
        setMealService.saveWithDish(setmealDTO);
        return ResultInfo.success(null, "套餐添加成功");
    }

    /**
     * 分页查询套餐列表
     *
     * @param pageNumber
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public ResultInfo<Page<SetmealDTO>> page(@RequestParam("page") int pageNumber, @RequestParam("pageSize") int pageSize, @RequestParam(value = "name", required = false, defaultValue = "") String name) {
        log.info("开始分页查询套餐列表。。。");
        Page<SetMeal> setMealPage = new Page<>(pageNumber, pageSize);
        Page<SetmealDTO> resultPage = new Page<>(pageNumber, pageSize);
        //分页查询SetMeal数据
        LambdaQueryWrapper<SetMeal> setMealLambdaQueryWrapper = new LambdaQueryWrapper<>();
        setMealLambdaQueryWrapper.like(name != null, SetMeal::getName, name);
        setMealLambdaQueryWrapper.orderByDesc(SetMeal::getUpdateTime);
        setMealService.page(setMealPage, setMealLambdaQueryWrapper);
        //将分页page通用信息（total、size等）赋值给resultPage
        BeanUtils.copyProperties(resultPage, setMealPage, "records");
        //获取categoryName后，将SetMeal数据赋值给SetmealDTO
        List<SetMeal> pageRecords = setMealPage.getRecords();
        List<SetmealDTO> realRecords = pageRecords.stream().map((item) -> {
            SetmealDTO setmealDTO = new SetmealDTO();
            BeanUtils.copyProperties(item, setmealDTO);
            Category category = categoryService.getById(item.getCategoryId());
            if (null != category) {
                setmealDTO.setCategoryName(category.getName());
            }
            return setmealDTO;
        }).collect(Collectors.toList());
        //将SetMeal的records数据，写入到resultPage中并返回
        resultPage.setRecords(realRecords);
        return ResultInfo.success(resultPage);
    }

    /**
     * 删除套餐
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public ResultInfo<String> deleteByIds(@RequestParam("ids") List<Long> ids) {
        log.info("要删除的套餐id为：{}", ids);
        if (CollectionUtils.isEmpty(ids)) {
            return ResultInfo.error("请传入欲删除的套餐ID");
        }
        setMealService.deleteWithDish(ids);
        return ResultInfo.success(null, "删除成功");
    }

    /**
     * 根据categoryId获取套餐信息
     * value 缓存的名称，在 spring配置文件中定义，必须指定至少一个
     * key 缓存的key，可以为空，如果指定要按照SpEL表达式编写，如果不指定，则缺省按照方法的所有参数进行组合
     * condition 缓存的条件，可以为空，使用SpEL编写，返回true或者false，只有为true 才进行缓存，如condition=”#userName.length()>2”
     *
     * @param setmeal
     * @return
     */
    @Cacheable(value = "setmealCache", key = "#setmeal.categoryId + '_' + #setmeal.status")
    @GetMapping("/list")
    public ResultInfo<List<SetMeal>> list(SetMeal setmeal) {
        //条件构造器
        LambdaQueryWrapper<SetMeal> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.eq(setmeal.getCategoryId() != null, SetMeal::getCategoryId, setmeal.getCategoryId());
        queryWrapper.eq(setmeal.getStatus() != null, SetMeal::getStatus, 1);
        //排序
        queryWrapper.orderByDesc(SetMeal::getUpdateTime);
        List<SetMeal> setmealList = setMealService.list(queryWrapper);
        return ResultInfo.success(setmealList);
    }

    /**
     * 根据套餐id查询套餐下的菜品信息
     *
     * @param id
     * @return
     */
    @GetMapping("/dish/{id}")
    public ResultInfo<List<DishDTO>> showSetmealDish(@PathVariable Long id) {
        //条件构造器
        LambdaQueryWrapper<SetmealDish> dishLambdaQueryWrapper = new LambdaQueryWrapper<>();
        //手里的数据只有setmealId
        dishLambdaQueryWrapper.eq(SetmealDish::getSetmealId, id);
        //查询数据
        List<SetmealDish> records = setmealDishService.list(dishLambdaQueryWrapper);
        List<DishDTO> dtoList = records.stream().map((item) -> {
            DishDTO dishDto = new DishDTO();
            //copy数据
            BeanUtils.copyProperties(item, dishDto);
            //查询对应菜品id
            Long dishId = item.getDishId();
            //根据菜品id获取具体菜品数据，这里要自动装配 dishService
            Dish dish = dishService.getById(dishId);
            //其实主要数据是要那个图片，不过我们这里多copy一点也没事
            BeanUtils.copyProperties(dish, dishDto);
            return dishDto;
        }).collect(Collectors.toList());
        return ResultInfo.success(dtoList);
    }

    /**
     * 停售/起售套餐
     *
     * @param status
     * @param ids
     * @return
     */
    //设置allEntries为true，清空缓存名称为setmealCache的所有缓存
    @CacheEvict(value = "setmealCache", allEntries = true)
    @PostMapping("/status/{status}")
    public ResultInfo<String> status(@PathVariable String status, @RequestParam List<Long> ids) {
        LambdaUpdateWrapper<SetMeal> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.in(SetMeal::getId, ids);
        updateWrapper.set(SetMeal::getStatus, status);
        setMealService.update(updateWrapper);
        return ResultInfo.success("批量操作成功");
    }

    /**
     * 根基套餐id获取套餐详情
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public ResultInfo<SetmealDTO> getById(@PathVariable Long id) {
        SetMeal setmeal = setMealService.getById(id);
        SetmealDTO setmealDto = new SetmealDTO();
        //拷贝数据
        BeanUtils.copyProperties(setmeal, setmealDto);
        //条件构造器
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        //根据setmealId查询具体的setmealDish
        queryWrapper.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> setmealDishes = setmealDishService.list(queryWrapper);
        //然后再设置属性
        setmealDto.setSetmealDishes(setmealDishes);
        //作为结果返回
        return ResultInfo.success(setmealDto);
    }

    /**
     * 修改套餐数据
     *
     * @param setmealDto
     * @return
     */
    //设置allEntries为true，清空缓存名称为setmealCache的所有缓存
    @CacheEvict(value = "setmealCache", allEntries = true)
    @PutMapping
    public ResultInfo<SetMeal> updateWithDish(@RequestBody SetmealDTO setmealDto) {
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        Long setmealId = setmealDto.getId();
        //先根据id把setmealDish表中对应套餐的数据删了
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, setmealId);
        setmealDishService.remove(queryWrapper);
        //然后在重新添加
        setmealDishes = setmealDishes.stream().map((item) -> {
            //这属性没有，需要我们手动设置一下
            item.setSetmealId(setmealId);
            return item;
        }).collect(Collectors.toList());
        //更新套餐数据
        setMealService.updateById(setmealDto);
        //更新套餐对应菜品数据
        setmealDishService.saveBatch(setmealDishes);
        return ResultInfo.success(setmealDto);
    }

}